<?php
class BDA_API {
    public static function init() {
        add_action('rest_api_init', [__CLASS__, 'register_routes']);
    }
    
    public static function register_routes() {
        register_rest_route('bda/v1', '/analytics', [
            'methods' => 'GET',
            'callback' => [__CLASS__, 'get_analytics'],
            'permission_callback' => function() {
                return current_user_can('manage_options');
            }
        ]);
        
        register_rest_route('bda/v1', '/user-segments', [
            'methods' => 'GET',
            'callback' => [__CLASS__, 'get_user_segments'],
            'permission_callback' => function() {
                return current_user_can('manage_options');
            }
        ]);
        
        register_rest_route('bda/v1', '/export-report', [
            'methods' => 'POST',
            'callback' => [__CLASS__, 'export_report'],
            'permission_callback' => function() {
                return current_user_can('manage_options');
            }
        ]);
    }
    
    public static function get_analytics(WP_REST_Request $request) {
        global $wpdb;
        
        $params = $request->get_params();
        $start_date = sanitize_text_field($params['start_date'] ?? date('Y-m-01'));
        $end_date = sanitize_text_field($params['end_date'] ?? date('Y-m-d'));
        
        // Basic sales data
        $sales_data = $wpdb->get_results($wpdb->prepare(
            "SELECT DATE(purchase_date) as date, 
                    SUM(total_price) as revenue, 
                    COUNT(DISTINCT order_id) as orders,
                    SUM(quantity) as items_sold
             FROM {$wpdb->prefix}analytics_purchases
             WHERE purchase_date BETWEEN %s AND %s
             GROUP BY DATE(purchase_date)",
            $start_date, $end_date
        ));
        
        return [
            'sales' => $sales_data,
            'start_date' => $start_date,
            'end_date' => $end_date
        ];
    }
    
    public static function get_user_segments(WP_REST_Request $request) {
        $params = $request->get_params();
        $start_date = sanitize_text_field($params['start_date'] ?? date('Y-m-01'));
        $end_date = sanitize_text_field($params['end_date'] ?? date('Y-m-d'));
        
        $segments = BDA_Analytics::get_user_segments($start_date, $end_date);
        
        // 分析用户画像
        $segment_analysis = [
            'total_users' => count($segments),
            'high_value' => 0,
            'medium_value' => 0,
            'low_value' => 0,
            'categories' => [],
            'geography' => []
        ];
        
        foreach ($segments as $user) {
            // 按消费能力分类
            if ($user->total_spent > 5) {
                $segment_analysis['high_value']++;
            } elseif ($user->total_spent > 0.5) {
                $segment_analysis['medium_value']++;
            } else {
                $segment_analysis['low_value']++;
            }
            
            // 按商品类别分类
            if (!isset($segment_analysis['categories'][$user->top_category])) {
                $segment_analysis['categories'][$user->top_category] = 0;
            }
            $segment_analysis['categories'][$user->top_category]++;
            
            // 按地理分类
            $country = self::ip_to_country($user->ip_address);
            if (!isset($segment_analysis['geography'][$country])) {
                $segment_analysis['geography'][$country] = 0;
            }
            $segment_analysis['geography'][$country]++;
        }
        
        return [
            'segments' => $segments,
            'analysis' => $segment_analysis,
            'start_date' => $start_date,
            'end_date' => $end_date
        ];
    }
    
    public static function export_report(WP_REST_Request $request) {
        // 确保没有输出缓冲干扰
        if (ob_get_level()) {
            ob_end_clean();
        }
        
        try {
            $params = $request->get_params();
            $start_date = sanitize_text_field($params['start_date'] ?? date('Y-m-01'));
            $end_date = sanitize_text_field($params['end_date'] ?? date('Y-m-d'));
            $export_type = sanitize_text_field($params['export_type'] ?? 'pdf');
            
            // 获取销售数据
            $sales_data = self::get_analytics($request);
            // 获取用户画像数据
            $user_segments = self::get_user_segments($request);
            
            if ($export_type === 'pdf') {
                // 检查TCPDF是否存在
                $tcpdf_path = BDA_PLUGIN_DIR . 'includes/tcpdf/tcpdf.php';
                if (!file_exists($tcpdf_path)) {
                    throw new Exception('TCPDF library not found');
                }
                
                require_once($tcpdf_path);
                
                // 创建新的PDF文档
                $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
                
                // 设置文档信息
                $pdf->SetCreator('Big Data Analytics');
                $pdf->SetAuthor('Big Data Analytics');
                $pdf->SetTitle('Analytics Report');
                $pdf->SetSubject('Analytics Report');
                
                // 添加一页
                $pdf->AddPage();
                
                // 设置字体
                $pdf->SetFont('helvetica', 'B', 16);
                
                // 标题
                $pdf->Cell(0, 10, 'Big Data Analytics Report', 0, 1, 'C');
                $pdf->SetFont('helvetica', '', 12);
                $pdf->Cell(0, 10, "Date Range: {$start_date} to {$end_date}", 0, 1, 'C');
                $pdf->Ln(10);
                
                // 销售数据部分
                $pdf->SetFont('helvetica', 'B', 14);
                $pdf->Cell(0, 10, 'Sales Data', 0, 1);
                $pdf->SetFont('helvetica', '', 12);
                
                // 销售数据表格
                $html = '<table border="1" cellpadding="4">
                    <tr>
                        <th width="25%">Date</th>
                        <th width="25%">Revenue</th>
                        <th width="25%">Orders</th>
                        <th width="25%">Items Sold</th>
                    </tr>';
                
                foreach ($sales_data['sales'] as $sale) {
                    $html .= '<tr>
                        <td>'.esc_html($sale->date).'</td>
                        <td>'.esc_html($sale->revenue).'</td>
                        <td>'.esc_html($sale->orders).'</td>
                        <td>'.esc_html($sale->items_sold).'</td>
                    </tr>';
                }
                
                $html .= '</table>';
                $pdf->writeHTML($html, true, false, false, false, '');
                $pdf->Ln(10);
                
                // 用户画像部分
                $pdf->SetFont('helvetica', 'B', 14);
                $pdf->Cell(0, 10, 'User Segments Analysis', 0, 1);
                $pdf->SetFont('helvetica', '', 12);
                
                // 用户分类统计
                $html = '<table border="1" cellpadding="4">
                    <tr>
                        <th width="25%">Segment</th>
                        <th width="25%">Count</th>
                        <th width="25%">Percentage</th>
                        <th width="25%">Description</th>
                    </tr>
                    <tr>
                        <td>High Value Users</td>
                        <td>'.esc_html($user_segments['analysis']['high_value']).'</td>
                        <td>'.esc_html(round($user_segments['analysis']['high_value']/$user_segments['analysis']['total_users']*100, 2)).'%</td>
                        <td>Total spent > $1000</td>
                    </tr>
                    <tr>
                        <td>Medium Value Users</td>
                        <td>'.esc_html($user_segments['analysis']['medium_value']).'</td>
                        <td>'.esc_html(round($user_segments['analysis']['medium_value']/$user_segments['analysis']['total_users']*100, 2)).'%</td>
                        <td>Total spent $500-$1000</td>
                    </tr>
                    <tr>
                        <td>Low Value Users</td>
                        <td>'.esc_html($user_segments['analysis']['low_value']).'</td>
                        <td>'.esc_html(round($user_segments['analysis']['low_value']/$user_segments['analysis']['total_users']*100, 2)).'%</td>
                        <td>Total spent < $500</td>
                    </tr>
                </table>';
                
                $pdf->writeHTML($html, true, false, false, false, '');
                $pdf->Ln(10);
                
                // 热门类别
                $pdf->SetFont('helvetica', 'B', 12);
                $pdf->Cell(0, 10, 'Top Categories', 0, 1);
                $pdf->SetFont('helvetica', '', 10);
                
                $html = '<table border="1" cellpadding="4">
                    <tr>
                        <th width="50%">Category ID</th>
                        <th width="50%">User Count</th>
                    </tr>';
                
                foreach ($user_segments['analysis']['categories'] as $cat_id => $count) {
                    $html .= '<tr>
                        <td>'.esc_html($cat_id).'</td>
                        <td>'.esc_html($count).'</td>
                    </tr>';
                }
                
                $html .= '</table>';
                $pdf->writeHTML($html, true, false, false, false, '');
                $pdf->Ln(10);
                
                // 地理分布
                $pdf->SetFont('helvetica', 'B', 12);
                $pdf->Cell(0, 10, 'User Geography', 0, 1);
                $pdf->SetFont('helvetica', '', 10);
                
                $html = '<table border="1" cellpadding="4">
                    <tr>
                        <th width="50%">Country</th>
                        <th width="50%">User Count</th>
                    </tr>';
                
                foreach ($user_segments['analysis']['geography'] as $country => $count) {
                    $html .= '<tr>
                        <td>'.esc_html($country).'</td>
                        <td>'.esc_html($count).'</td>
                    </tr>';
                }
                
                $html .= '</table>';
                $pdf->writeHTML($html, true, false, false, false, '');
                
                // 生成PDF内容
                $filename = "analytics-report-{$start_date}-to-{$end_date}.pdf";
                $pdf_content = $pdf->Output($filename, 'S');
                
                // 返回JSON响应
                return new WP_REST_Response([
                    'success' => true,
                    'filename' => $filename,
                    'content' => base64_encode($pdf_content),
                    'type' => 'pdf'
                ], 200);
                
            } else {
                // 生成CSV内容
                $csv_content = "Big Data Analytics Report\n";
                $csv_content .= "Date Range: {$start_date} to {$end_date}\n\n";
                
                // 销售数据部分
                $csv_content .= "Sales Data\n";
                $csv_content .= "Date,Revenue,Orders,Items Sold\n";
                foreach ($sales_data['sales'] as $sale) {
                    $csv_content .= "{$sale->date},{$sale->revenue},{$sale->orders},{$sale->items_sold}\n";
                }
                
                // 用户画像部分
                $csv_content .= "\nUser Segments Analysis\n";
                $csv_content .= "Total Users,High Value,Medium Value,Low Value\n";
                $csv_content .= "{$user_segments['analysis']['total_users']},{$user_segments['analysis']['high_value']},{$user_segments['analysis']['medium_value']},{$user_segments['analysis']['low_value']}\n\n";
                
                $csv_content .= "Top Categories\n";
                $csv_content .= "Category ID,User Count\n";
                foreach ($user_segments['analysis']['categories'] as $cat_id => $count) {
                    $csv_content .= "{$cat_id},{$count}\n";
                }
                
                $csv_content .= "\nUser Geography\n";
                $csv_content .= "Country,User Count\n";
                foreach ($user_segments['analysis']['geography'] as $country => $count) {
                    $csv_content .= "{$country},{$count}\n";
                }
                
                $filename = "analytics-report-{$start_date}-to-{$end_date}.csv";
                
                // 返回JSON响应
                return new WP_REST_Response([
                    'success' => true,
                    'filename' => $filename,
                    'content' => $csv_content,
                    'type' => 'csv'
                ], 200);
            }
            
        } catch (Exception $e) {
            // 返回错误信息
            return new WP_REST_Response([
                'success' => false,
                'message' => '导出报告失败: ' . $e->getMessage()
            ], 500);
        }
    }
    
    private static function ip_to_country($ip) {
        // 跳过本地 IP
        if ($ip === '127.0.0.1' || substr($ip, 0, 8) === '192.168.') {
            return 'Local';
        }
    
        $url = "http://ip-api.com/json/$ip?fields=country";
        try {
            $response = file_get_contents($url);
            $data = json_decode($response, true);
            return $data['country'] ?? 'Unknown';
        } catch (\Exception $e) {
            return 'Unknown';
        }
    }
}